package com.sc.demo2.test;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.sc.demo2.common.util.PDFUtil;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.HashMap;

public class PDFTest1 {
    public static void main(String[] args) throws Exception {
        // 模板
        String templateFilePath = PDFUtil.getResourcePath() + "contract\\pdf\\template.pdf";

        // 填充表单后的pdf
        String pdfFilePath = PDFUtil.getResourcePath() + "contract\\pdf\\template1.pdf";

        // 加入印章并签名的pdf存储目录
        String pdfSignFilePath = PDFUtil.getResourcePath() + "contract\\pdf\\template_sign.pdf";

        // 加入手写签名的pdf存储目录
        String pdfSignFilePath1 = PDFUtil.getResourcePath() + "contract\\pdf\\template_sign1.pdf";

        // 电子印章图片
        String sealFilePath = PDFUtil.getResourcePath() + "contract\\seal.gif";

        // 手写签名图片
        String signPngFilePath = PDFUtil.getResourcePath() + "contract\\signature.png";

        // 证书位置
        String p12FilePath = PDFUtil.getResourcePath() + "contract\\wust.p12";

        String pwd = "111111";

        // 表单文本域数据
        HashMap<String, String> formData = new HashMap<>();
        formData.put("text_0", "XXX科技开发有限公司");
        formData.put("text_6", "张三");
        formData.put("text_7", "男");
        formData.put("text_8", "50");
        formData.put("text_9", "452828299908879221");
        formData.put("text_10", "2020");
        formData.put("text_11", "7");
        formData.put("text_12", "27");

        // 表单签名域数据：公章图片和手势图片
        HashMap<String, String> signatureData = new HashMap<>();
        signatureData.put("signature_0", PDFUtil.getResourcePath() + "contract\\seal.gif");
        signatureData.put("signature_1", PDFUtil.getResourcePath() + "contract\\signature.png");

        PDFUtil.createPDF(templateFilePath, pdfFilePath, formData, false);

        PDFUtil.sign(pdfFilePath,
                pdfSignFilePath,
                p12FilePath,
                pwd,
                "手势签名，不可更改",
                "平台",
                "signature_1",
                signPngFilePath,
                true);


        PDFUtil.sign(pdfSignFilePath,
                pdfSignFilePath1,
                p12FilePath,
                pwd,
                "电子印章，不可更改",
                "平台",
                "signature_0",
                sealFilePath,
                true);
    }


    /**
     * 根据PDF模版生成PDF文件
     *
     * @param pdfTemplateFilePath PDF模版文件路径
     * @param pdfSignFilePath      签名后的PDF的文件路径
     * @param formData         表单数据
     * @param signatureData        图片数据 VALUE为图片文件路径
     * @param formFlattening   false：生成后的PDF文件表单域仍然可编辑 true：生成后的PDF文件表单域不可编辑

     */
    private static void createPDF(String pdfTemplateFilePath,
                                  String pdfSignFilePath,
                                  HashMap<String, String> formData,
                                  HashMap<String, String> signatureData,
                                  boolean formFlattening
                                  ) throws Exception {
        PdfReader reader = null;
        ByteArrayOutputStream bos = null;
        PdfStamper pdfStamper = null;
        FileOutputStream fos = null;
        try {
            // 读取PDF模版文件
            reader = new PdfReader(pdfTemplateFilePath);

            // 输出流
            bos = new ByteArrayOutputStream();

            // 构建PDF对象
            pdfStamper = new PdfStamper(reader, bos);

            // 获取表单数据
            AcroFields form = pdfStamper.getAcroFields();

            // 使用中文字体 使用 AcroFields填充值的不需要在程序中设置字体，在模板文件中设置字体为中文字体 Adobe 宋体 std L
            BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(bfChinese);

            // 表单赋值
            for (String key : formData.keySet()) {
                form.setField(key, formData.get(key));
                // 也可以指定字体
                form.setFieldProperty(key, "textfont", bfChinese, null);
            }

            // 添加图片
            if (null != signatureData && signatureData.size() > 0) {
                for (String key : signatureData.keySet()) {
                    int pageNo = form.getFieldPositions(key).get(0).page;
                    Rectangle signRect = form.getFieldPositions(key).get(0).position;
                    float x = signRect.getLeft();
                    float y = signRect.getBottom();
                    // 读图片
                    Image image = Image.getInstance(signatureData.get(key));
                    // 获取操作的页面
                    PdfContentByte under = pdfStamper.getOverContent(pageNo);
                    // 根据域的大小缩放图片
                    image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                    // 添加图片
                    image.setAbsolutePosition(x, y);
                    under.addImage(image);
                }
            }

            pdfStamper.setFormFlattening(formFlattening);
            pdfStamper.close();

            // 保存文件
            fos = new FileOutputStream(pdfSignFilePath);
            fos.write(bos.toByteArray());
            fos.flush();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (null != bos) {
                try {
                    bos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (null != reader) {
                try {
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
